#include	<QDataStream>
#include	"QtTCPSocket.h"

QtTCPSocket::QtTCPSocket()
  : _socket(NULL), _hostName(QString()), _port(80)
{
}

QtTCPSocket::QtTCPSocket(std::string& hostName, unsigned int port = 80)
  : _socket(NULL), _hostName(QString(hostName.c_str())), _port(port)
{
  this->_socket = new QTcpSocket(this);
  QObject::connect(this->_socket, SIGNAL(QIODevice::readyRead()), this, SLOT(onRead()));
  connect();
}

QtTCPSocket::~QtTCPSocket()
{
  delete _socket;
}

QtTCPSocket& QtTCPSocket::operator=(const QtTCPSocket& obj)
{
  if (this != &obj)
    {
      //TODO
    }
  return (*this);
}

void QtTCPSocket::connect()
{
  this->close();
  this->_socket->connectToHost(this->_hostName, this->_port);
}

void QtTCPSocket::accept()
{
}

void QtTCPSocket::close()
{
  this->_socket->abort();
}

int QtTCPSocket::read(std::string& buffer)
{
  unsigned int size = this->_buffer.count();
  if (this->_socket->isReadable())
    {      
      buffer = this->_buffer.toStdString();
      this->_buffer.clear();
    }
  return (size);
}

int QtTCPSocket::write(std::string& buffer, unsigned int size)
{
  buffer = buffer;
  size = size;
  return (0);
}

void QtTCPSocket::onRead()
{
  if (this->_socket->isReadable())
    {      
      QDataStream in(this->_socket);
      QString temp;
  
      in >> temp;
      this->_buffer += temp;
    }
}
